import requests
import winsound
import json
import time
import random
import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr
from concurrent.futures import ThreadPoolExecutor

# 把Cookies内容整个复制到字符串中，末尾不能有其他无关字符（如空格，分号等）
Cookies = "JSESSIONID=FEEF1D9DCBCBF5EDAEDED6C78F6B2CAF; route=5d2a6d47337e9ab79f3b785b88056503"
cookies = {}
for cookie in Cookies.split('; '):
    key, value = cookie.split('=')
    cookies[key] = value

headers = {
    'Accept': 'application/json, text/javascript, */*; q=0.01',
    'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
    'Connection': 'keep-alive',
    'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
    # 'Cookie': 'JSESSIONID=8D623456E4E8014CFC4B27EE4911AE8E; route=ea0904e1f60731f45f8ffa63eae37fca',
    'Origin': 'https://jwgl.nwu.edu.cn',
    'Referer': 'https://jwgl.nwu.edu.cn/jwglxt/xsxk/zzxkyzb_cxZzxkYzbIndex.html?gnmkdm=N253512&layout=default&su=2022117321',
    'Sec-Fetch-Dest': 'empty',
    'Sec-Fetch-Mode': 'cors',
    'Sec-Fetch-Site': 'same-origin',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 Edg/120.0.0.0',
    'X-Requested-With': 'XMLHttpRequest',
    'sec-ch-ua': '"Not_A Brand";v="8", "Chromium";v="120", "Microsoft Edge";v="120"',
    'sec-ch-ua-mobile': '?0',
    'sec-ch-ua-platform': '"Windows"',
}

params = {
    'gnmkdm': 'N253512',
    'su': '2022117321',
}

my_sender = '467029499@qq.com'  # 填写发信人的邮箱账号
my_pass = 'wzeqrboozqwycajb'  # 发件人邮箱授权码
my_user = '467029499@qq.com'  # 收件人邮箱账号


def mail(kcmc):
    ret = True
    try:
        msg = MIMEText(f'你抢的{kcmc}课抢上啦！', 'plain', 'utf-8')  # 填写邮件内容
        msg['From'] = formataddr(["AutoPickClass", my_sender])  # 括号里的对应发件人邮箱昵称、发件人邮箱账号
        msg['To'] = formataddr(["test", my_user])  # 括号里的对应收件人邮箱昵称、收件人邮箱账号
        msg['Subject'] = "抢课成功啦！"  # 邮件的主题，也可以说是标题

        server = smtplib.SMTP_SSL("smtp.qq.com", 465)  # 发件人邮箱中的SMTP服务器
        server.login(my_sender, my_pass)  # 括号中对应的是发件人邮箱账号、邮箱授权码
        server.sendmail(my_sender, [my_user, ], msg.as_string())  # 括号中对应的是发件人邮箱账号、收件人邮箱账号、发送邮件
        server.quit()  # 关闭连接
    except Exception:  # 如果 try 中的语句没有执行，则会执行下面的 ret=False
        ret = False
    return ret


def task(jxb_ids, kch_id, kcmc):
    data = {
        "jxb_ids": jxb_ids,
        "kch_id": kch_id,
        "kcmc": kcmc,
        "qz": "0",

        # "xkkz_id": "0CC0A20EBA420A5BE065000000000001",
        # "kcmc": "(U17M1313)%E8%AE%A1%E7%AE%97%E6%9C%BA%E7%BB%84%E6%88%90%E5%8E%9F%E7%90%86+-+3.0+%E5%AD%A6%E5%88%86",
        # "rwlx": "1",
        # "rlkz": "0",
        # "rlzlkz": "0",
        # "sxbj": "0",
        # "xxkbj": "0",
        # "cxbj": "0",
        # "njdm_id": "2022",
        # "zyh_id": "1805",
        # "kklxdm": "01",
        # "xklc": "1",
        # "xkxnm": "2023",
        # "xkxqm": "12"
    }

    while True:
        response = requests.post(
            'https://jwgl.nwu.edu.cn/jwglxt/xsxk/zzxkyzbjk_xkBcZyZzxkYzb.html',
            params=params,
            cookies=cookies,
            headers=headers,
            data=data,
        )
        res = json.loads(response.text)
        flag = res['flag']
        localtime = time.asctime(time.localtime(time.time()))
        if flag == "-1":
            print(localtime, "人满，暂时无法选课", kcmc)
        if flag == "0":
            print(localtime, res["msg"], kcmc)
        if flag == "1":
            print(localtime, "选课成功！", kcmc)
            # winsound.Beep(440, 1000)  # 响铃1秒钟，频率440Hz
            ret = mail(kcmc)  # 自动发邮件模块
            if ret:
                print("邮件发送成功")
            else:
                print("邮件发送失败")
            break

        time.sleep(random.random())


def run():
    ke = [  # 每次在里面添加jxb_ids,kch_id(,课程名称)即可
        [
            "43b2ac7a628b06b1f51ba6b38181e4210c4f8ae81805bf2110c60617c0fbecb4c4223117bb8b7a6e3cc16d74ca2397fc72ebe7b8a36f5358689bfbd2330c44baf83243de75020c4d5c5def7a94f6d00f71757022b6a48123d50511ab3d8550955028ad3940806dc4ce8eef0fbf2c4b2279a6ed18ac20cd43010b102b8470418a",
            "U22G1002", "乒乓球-安江"],
        # [
        #     "",
        #     "U09C1005", "古典音乐鉴赏(spoc)"],
        [
            "755523ce33d6d32857e00c7761cc6562d5d7a03dc17d1aa97163cecd60d705114990496d98e673ed7c1636ef4fcf6d90d46f256a3cc455094e8a91ef341c9b665da9152825a215de6c02476fad3afcfc02ea50d686f2278b43f95f7cba0d468765dd3a2b7250c1b0b6b3eb41f9c39800006f5d2372875ac66133bbaf89713162",
            "U22G1024", "李强-射艺"
        ]

    ]
    with ThreadPoolExecutor(5) as t:
        for k in ke:
            jxb_ids = k[0]
            kch_id = k[1]
            kcmc = k[2]
            t.submit(task, jxb_ids, kch_id, kcmc)


if __name__ == '__main__':
    run()
